import { Init, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { GoodsPromoTcEntity } from '../entity/promo_tc';

/**
 * 促销套餐服务
 */
@Provide()
export class GoodsPromoTcService extends BaseService {
  @InjectEntityModel(GoodsPromoTcEntity)
  promoTcEntity: Repository<GoodsPromoTcEntity>;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.promoTcEntity);
  }

  /**
   * 根据单据号获取套餐明细
   * @param billNo 单据号
   */
  async getByBillNo(billNo: string) {
    return await this.promoTcEntity.find({
      where: { billNo, status: 1 },
      order: { billSn: 'ASC' }
    });
  }

  /**
   * 根据商品ID获取套餐促销
   * @param goodsId 商品ID
   */
  async getByGoodsId(goodsId: string) {
    return await this.promoTcEntity.find({
      where: { goodsId, status: 1 },
      order: { createTime: 'DESC' }
    });
  }

  /**
   * 获取所有套餐促销明细
   */
  async getAllActiveDetails() {
    return await this.promoTcEntity.find({
      where: { status: 1 },
      order: { createTime: 'DESC' }
    });
  }

  /**
   * 计算套餐总价
   * @param billNo 单据号
   */
  async calculateComboPrice(billNo: string) {
    const details = await this.getByBillNo(billNo);
    return details.reduce((total, item) => total + (item.taxprice * item.num), 0);
  }
} 